<script setup>
import { ref, watch, watchEffect } from 'vue';
import { ElMessage } from 'element-plus';
import { common } from '@utils';
import { Plus } from '@element-plus/icons-vue';
import { SERVE_URL, imgSERVEURL } from '@utils/config';
import store from '@store';
/**
 * 后面如果传入的不是图片可以加个type来判断，暂时写死图片
 */
const props = defineProps({
    limit: {
        default: 1,
        type: Number,
    },
    width: Number,
    height: Number,
    modelValue: {
        type: [String, Array],
    },
    size: {
        default: 1024,
        type: Number,
    },
    showTip: {
        default: false,
        type: Boolean,
    },
    paramData: {
        default: { targetCode: 'biz_goods' },
        type: Object,
    },
});

const emit = defineEmits(['update:modelValue', 'change']);

const fileList = ref([]);

const dialogImageUrl = ref('');
const dialogVisible = ref(false);
watch(
    () => props.modelValue,
    async (newVal, oldVal) => {
        if (newVal) {
            if (typeof newVal === 'string') {
                fileList.value = [{ url: imgSERVEURL + newVal }];
            } else {
                fileList.value = newVal.map(item => ({ url: imgSERVEURL + item }));
            }
        }
    },
    { immediate: true }
);
// watchEffect(() => {
//     // 用来做响应性追踪
//     let newVal = props.modelValue;
//     if (newVal) {
//         if (typeof newVal == 'string') {
//             let imgUrl = newVal.split(',');
//             fileList.value = imgUrl.map(item => ({ url: imgSERVEURL + item }));
//         } else {
//             fileList.value = newVal.map(item => ({ url: imgSERVEURL + item }));
//         }
//     }
//     // onCleanup(() => {
//     //     newVal.cancel();
//     // });
// });
// let newVal = props.modelValue;
// if (newVal) {
//     if (typeof newVal == 'string') {
//         let imgUrl = newVal.split(',');
//         fileList.value = imgUrl.map(item => ({ url: imgSERVEURL + item }));
//     } else {
//         fileList.value = newVal.map(item => ({ url: imgSERVEURL + item }));
//     }
// }
const header = ref({ Authorization: store.getters.token });

const beforeUpload = file => {
    const isJPG = file.type === 'image/webp' || file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
    const isLt = file.size / 1024 <= props.size;

    if (!isJPG) {
        ElMessage.warning('上传图片只能是 webp jpg jpeg png 格式!');
    }

    if (!isLt) {
        ElMessage.warning(`上传图片大小不能超过 ${props.size > 1024 ? props.size / 1024 + 'MB' : props.size + 'KB'}!`);
    }
    return isJPG && isLt;
};

const fileStyle = {
    width: (props.width || 100) + 'px',
    height: (props.height || 100) + 'px',
};

const handleRemove = (uploadFile, uploadFiles) => {
    updateModel();
};

const handleSuccess = (response, file) => {
    fileList.value.forEach(item => {
        if (item.response && item.response.data) {
            item.url = imgSERVEURL + item.response.data.fileUrl;
        }
    });
    updateModel();
};

const updateModel = () => {
    let res = null;
    if (fileList.value && fileList.value.length > 0) {
        if (fileList.value.length === 1 && props.limit === 1) {
            res = fileList.value[0].url.replace(imgSERVEURL, '');
        } else {
            res = fileList.value.map(item => item.url.replace(imgSERVEURL, ''));
        }
    }
    emit('update:modelValue', res);
    emit('change');
};

const handlePictureCardPreview = uploadFile => {
    dialogImageUrl.value = uploadFile.url;
    dialogVisible.value = true;
};

//超出限制
const handleExceed = () => {
    ElMessage.warning('超出个数限制!');
};
</script>
<template>
    <div>
        <el-upload :class="fileList.length >= limit ? 'visbileDiv' : ''" v-model:file-list="fileList" v-bind="$attrs" :action="SERVE_URL + 'apiExp/oss/file/upload'" list-type="picture-card" :on-preview="handlePictureCardPreview" :limit="limit" :headers="header" :before-upload="beforeUpload" :on-remove="handleRemove" :on-success="handleSuccess" :on-exceed="handleExceed" :data="paramData">
            <el-icon><Plus></Plus></el-icon>
        </el-upload>
        <div class="color-3" v-if="showTip">
            {{ `上传图片大小不能超过 ${props.size >= 1024 ? props.size / 1024 + 'MB' : props.size + 'KB'}!` }}
        </div>
        <el-dialog v-model="dialogVisible">
            <img class="width100" :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
.upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px !important;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
:deep(.el-upload--picture-card) {
    --el-upload-picture-card-size: 110px;
}
:deep(.el-upload-list--picture-card) {
    --el-upload-list-picture-card-size: 110px;
}
:deep(.visbileDiv .el-upload--picture-card) {
    display: none !important;
}
</style>
